package com.frxuexi.shop.view

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.adapter.CartAdapter
import com.frxuexi.lib_base.alipay.MyPay
import com.frxuexi.lib_base.alipay.PayResult
import com.frxuexi.lib_base.alipay.util.OrderInfoUtil2_0
import com.frxuexi.lib_base.entity.CartBean
import com.frxuexi.lib_base.entity.CreateOrderReqBean
import com.frxuexi.lib_base.entity.CreateOrderRespBean
import com.frxuexi.lib_base.entity.LoadPreOrderBean
import com.frxuexi.lib_base.entity.OrderDetail
import com.frxuexi.lib_base.entity.PreOrderBean
import com.frxuexi.lib_base.entity.PreOrderResBean
import com.frxuexi.lib_base.mvi.BaseFragment
import com.frxuexi.lib_base.mvi.RequestType
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.shop.R
import com.frxuexi.shop.databinding.FragmentCartBinding
import com.frxuexi.shop.intent.CartIntent
import com.frxuexi.shop.intent.OrderIntent
import com.frxuexi.shop.viewmodel.CartViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@AndroidEntryPoint
class CartFragment : BaseFragment<FragmentCartBinding, CartIntent, CartViewModel>() {
    override val binding: FragmentCartBinding by lazy { FragmentCartBinding.inflate(layoutInflater) }
    override val vm: CartViewModel by viewModels<CartViewModel>()
    val cartAdapter by lazy { CartAdapter() }
    var sum = 0
    var orderNo=""//订单编号
    var uni=""//订单id
    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when (it.type) {
                            RequestType.DEFAULT -> {
                                cartAdapter.data.clear()
                                val cartBean = it.data as CartBean
                                cartAdapter.addData(cartBean.list)
                                cartAdapter.notifyDataSetChanged()
                                binding.cartNum.setText("购物车（${cartBean.list.size}）")
                            }

                            RequestType.UPDATE -> {

                            }
                            RequestType.ADD->{//预下单成功
                                val orderNoBean = it.data as PreOrderResBean
                                orderNo=orderNoBean.preOrderNo
                                vm.sendIntent(CartIntent.loadPreOrder(orderNoBean.preOrderNo))
                            }
                            RequestType.GETPRE_ORDER->{//加载预下单成功
                                val bean = it.data as LoadPreOrderBean
                                val reqBean = CreateOrderReqBean(
                                    bean.orderInfoVo.addressId,
                                    bean.orderInfoVo.userCouponId,
                                    bean.orderInfoVo.remark?:"",
                                    "alipay",
                                    "yue",
                                    bean.orderInfoVo.phone,
                                    orderNo,
                                    bean.orderInfoVo.realName,
                                    1,
                                    0,
                                    false
                                )
                                vm.sendIntent(CartIntent.createOrder(reqBean))
                            }
                            RequestType.CREATE->{//创建订单成功
                                val respBean = it.data as CreateOrderRespBean
                                uni=respBean.orderNo
                                MyPay.payV2(sum.toString(),requireActivity())
                            }
                            RequestType.PAY->{//接口支付成功
                                ARouter.getInstance().build("/shop/OrderActivity").navigation()
                            }
                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }
    }
    
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getPayResult(result:String){
        Log.i("lr",result)
        if(result=="payOk") {
            val map = hashMapOf<String, Any>(
                "from" to "",
                "orderNo" to uni,
                "payChannel" to "alipay",
                "payType" to "yue",
                "scene" to 0,
                "uni" to ""
            )
            vm.sendIntent(CartIntent.payOrder(map))
//
        }else{
            ToastUtils.showLong("支付失败")
        }
    }

    override fun initView() {
        EventBus.getDefault().register(this)
        binding.rvCar.apply {
            adapter = cartAdapter
            layoutManager = LinearLayoutManager(requireContext())
        }
        vm.sendIntent(CartIntent.getCarts("0"))

        binding.cbAll.setOnClickListener {
            cartAdapter.data.forEach {
                it.isCheck = binding.cbAll.isChecked
            }
            cartAdapter.notifyDataSetChanged()
            //计算总价
            if (binding.cbAll.isChecked) {
                sum = cartAdapter.data.sumOf {
                    it.cartNum * it.price
                }
                binding.buyNow.setText("结算(${cartAdapter.data.size})")
            } else {
                sum = 0
                binding.buyNow.setText("结算(0)")
            }
            binding.amountAll.setText("合计：￥${sum}")
        }

        binding.cartNum.setText("购物车（${cartAdapter.data.size})")

        cartAdapter.addChildClickViewIds(R.id.car_check_box, R.id.car_add, R.id.car_sub)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = cartAdapter.data.get(position)
            when (view.id) {
                R.id.car_check_box -> {
                    cartAdapter.data.get(position).isCheck = !item.isCheck
                    //联动全选的状态
                    binding.cbAll.isChecked = cartAdapter.data.all { it.isCheck }
                    //计算总价
                    if (cartAdapter.data.get(position).isCheck) {
                        sum += item.price * item.cartNum
                    } else {
                        sum -= item.price * item.cartNum
                    }

                    //选中的个数
                    val count = cartAdapter.data.count {
                        it.isCheck
                    }
                    binding.buyNow.setText("结算(${count})")
                }

                R.id.car_add -> {
                    item.cartNum++
                    vm.sendIntent(CartIntent.updateCart(item.id, item.cartNum))

                    //计算总价
                    if (item.isCheck) {
                        sum += item.price
                    }
                }

                R.id.car_sub -> {
                    if (item.cartNum == 1) {
                        ToastUtils.showLong("购买数量不能小于1")
                        return@setOnItemChildClickListener
                    }
                    item.cartNum--
                    vm.sendIntent(CartIntent.updateCart(item.id, item.cartNum))
                    //计算总价
                    if (item.isCheck) {
                        sum -= item.price
                    }
                }

            }
            cartAdapter.notifyItemChanged(position)
            binding.amountAll.setText("合计：￥${sum}")
        }

        binding.buyNow.setOnClickListener {
//            payV2(sum.toString())
            cartAdapter.data.filter { it.isCheck }
                .forEach {
                    val preOrderBean = PreOrderBean(
                        preOrderType = "shoppingCart",
                        productId = it.productId,
                        shoppingCartId = it.id,
                        orderDetails = listOf<OrderDetail>(
                            OrderDetail(preOrderType = "shoppingCart",
                                productId = it.productId,
                                shoppingCartId = it.id)
                        )
                    )
                    vm.sendIntent(CartIntent.preOrder(preOrderBean))
                }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}